package cn.wolfcode.wechat.controller;

import cn.wolfcode.wechat.domain.Client;
import cn.wolfcode.wechat.domain.Robotanswer;
import cn.wolfcode.wechat.domain.WelcomeMessage;
import cn.wolfcode.wechat.service.IClientService;
import cn.wolfcode.wechat.service.IRobotanswerService;
import cn.wolfcode.wechat.service.IWelcomeMessageService;
import cn.wolfcode.wechat.util.*;
import cn.wolfcode.wechat.vo.AnswerVo;
import cn.wolfcode.wechat.vo.MessageRequestVo;
import cn.wolfcode.wechat.vo.MessageResponseVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.TreeSet;

@Controller
@RequestMapping("wechat")
public class WechatControllor {
    public static String OPENID = "";
    @Value("${wechat.token}")
    private String token;
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;

    @Autowired
    private IClientService clientService;
    @Autowired
    private IWelcomeMessageService welcomeMessageService;

    @Autowired
    private IRobotanswerService robotanswerService;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String wechat(String signature, String timestamp, String nonce, String echostr) {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        TreeSet<String> treeSet = new TreeSet<>();
        treeSet.add(token);
        treeSet.add(timestamp);
        treeSet.add(nonce);
        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder sb = new StringBuilder();
        for (String str : treeSet) {
            sb.append(str);
        }
        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        String ret = SecurityUtil.SHA1(sb.toString());
        if (ret.equals(signature)) {
            return echostr;
        }
        return "false";
    }

    /**
     * 图灵机器人
     *
     * @param requestVo
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Object text(@RequestBody MessageRequestVo requestVo) {

        if ("event".equals(requestVo.getMsgType())) {
            return eventHandler(requestVo);
        }
        System.out.println(requestVo.getContent());
        String text = requestVo.getContent();
        if (text.equals("打人")) {
            TemplateController.robotfight(requestVo.getFromUserName());
            return null;
        }
        if (text.equals("打断手脚") || text.equals("打进医院") || text.equals("打成植物人") || text.equals("打到死")) {
            Robotanswer robotanswer = robotanswerService.selectByPrimaryKey(text);
            return sendMsg(requestVo, robotanswer.getCustomerId());
        } else {
            return sendMsg(requestVo, JSON.parseObject(HttpUtil.post("http://www.tuling123.com/openapi/api","key=33c05f7cb68843d38e0a5f1154706c19&info=" + requestVo.getContent()+"&userid="+OPENID), AnswerVo.class).getText());
        }
    }

    @RequestMapping("/welcomeMessage")
    public String welcomeMessage(Model model) {
        model.addAttribute("welcomeMessage", welcomeMessageService.get(1L));
        return "welcomeMessage";
    }

    @RequestMapping("/saveWelcomeMessage")
    @ResponseBody
    public JSONResult welcomeMessage(WelcomeMessage message) {
        try {
            welcomeMessageService.saveOrUpdate(message);
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, e.getMessage());
        }
    }

    /**
     * 抽取一个通用的文本信息方法
     *
     * @param requestVo
     * @param content
     * @return
     */
    private MessageResponseVo sendMsg(MessageRequestVo requestVo, String content) {
        MessageResponseVo responseVo = new MessageResponseVo();
        responseVo.setFromUserName(requestVo.getToUserName());
        responseVo.setToUserName(requestVo.getFromUserName());
        responseVo.setContent(content);
        responseVo.setCreateTime(System.currentTimeMillis());
        responseVo.setMsgType("text");
        return responseVo;
    }

    /**
     * 抽取一个事件推送(关注公众号)
     *
     * @param requestVo
     * @return
     */
    private MessageResponseVo eventHandler(MessageRequestVo requestVo) {
        String openid = requestVo.getFromUserName();
        if ("subscribe".equals(requestVo.getEvent())) {
            Client client = getClientMessage(openid);
            //保存关注测试号的客户信息
            clientService.save(client);
            WelcomeMessage welcomeMessage = welcomeMessageService.get(1L);
            return sendMsg(requestVo, welcomeMessage.getWelcomeMessage());
        } else if ("unsubscribe".equals(requestVo.getEvent())) {
            //取关的操作
            Client client = getClientMessage(openid);
            clientService.unsubscribe(client);
        } else if ("VIEW".equals(requestVo.getEvent())) {
            OPENID = requestVo.getFromUserName();
        }
        return null;
    }

    /**
     * 获取关注用户基本信息
     *
     * @return
     */
    private Client getClientMessage(String openid) {
        String getUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + AccessTokenUtil.getAccessTokenVo() + "&openid=" + openid + "&lang=zh_CN";
        String clientMessage = HttpsUtil.get(getUrl);
        Client client = JSON.parseObject(clientMessage, Client.class);
        return client;
    }
    private Robotanswer returnRobotanswer(String usercontent){
        Robotanswer robotanswer = new Robotanswer();
        robotanswer.setUsercontent(usercontent);
        return robotanswer;
    }

}
